import axios from 'axios'
import { ElMessage } from 'element-plus'

const urlString = window.location.href.split('#')[0]
const prefix = urlString.indexOf('test') != -1 ? '/test' : ''
const baseURL = prefix + import.meta.env.VITE_API_URL
const service = axios.create({
  baseURL,
  timeout: 10000
})
console.log(7, baseURL)
service.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    console.log(30, response)
    // if (!response.data.succeeded) {
    //     ElMessage .error(`${response.data.error_message}`)
    // }
    if (response.status === 200) {
      return response.data
    } else {
      Promise.reject()
    }
  },
  (error) => {
    console.log(42, error)
    switch (error.response.status) {
      case 500:
        error.message = '服务器内部错误'
        break
      case 400:
        error.message = '请求错误'
        break
      case 401:
        error.message = '未授权请求'
        break
      case 404:
        error.message = '请求地址错误'
        break
    }
    ElMessage.error(`${error.message}`)
    return Promise.reject(error)
  }
)

export default service
